<?php

namespace App\Models\Business;

use App\Models\Config as ConfigModel;
use App\Models\Region as RegionModel;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Business extends Model
{
    use HasFactory;

    // 指定的数据表
    protected $table = 'business';

    // 自动写入时间戳
    public $timestamps = true;

    // 时间类型
    protected $dateFormat = 'U';

    // 自定义创建时间字段
    const CREATED_AT = 'createtime';

    // 自定义更新时间字段
    const UPDATED_AT = null;

    protected $guarded = [];

    protected $appends = [
        'mobile_text',
        'region_text',
        'avatar_cdn',
        'gender_text'
    ];

    // 定义不存在字段
    public function getMobileTextAttribute()
    {
        return substr_replace($this->mobile,'****',3,4);
    }

    public function getRegionTextAttribute()
    {
        $province = RegionModel::where('code',$this->province)->value('name');
        $city = RegionModel::where('code',$this->city)->value('name');
        $district = RegionModel::where('code',$this->district)->value('name');
        
        $text = '';

        if($province)
        {
            $text = $province . '-';
        }

        if($city)
        {
            $text .= $city . '-';
        }

        if($district)
        {
            $text .= $district;
        }
    
        return $text;
    }

    // 定义不存在字段
    public function getAvatarCdnAttribute()
    {
        // 获取fastAdmin的地址
        $url = ConfigModel::where('name', 'url')->value('value');

        // 上面查询的fastAdmin地址可能是线上的，如果请在该项目.env环境配置文件新增一个配置项FastAdmin的本地开发地址
        $url = env('SITE_URL',$url);

        // 拼接接口
        $url = $url . '/base/business/avatar';

        $res = httpRequest($url,['busid' => $this->id]);

        return $res;
    }

    public function getGenderTextAttribute()
    {
        $GenderList = [0 => '保密',1 => '男',2 => '女'];

        return $GenderList[$this->gender];
    }
}
